package com.sinosoft.weixin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.sinosoft.weixin.config.InterfaceAdapterConfig;
import com.sinosoft.weixin.controller.dto.RequestDTO;
import com.sinosoft.weixin.controller.dto.RequestHeadDTO;
import com.sinosoft.weixin.controller.dto.request.RiskAssessDetailDTO;
import com.sinosoft.weixin.controller.dto.response.pdfDTO.*;
import com.sinosoft.weixin.controller.vo.Vo;
import com.sinosoft.weixin.service.ServiceException;
import com.sinosoft.weixin.utils.ArabicToChineseUtils;
import com.sinosoft.weixin.utils.HttpClientUtils;
import com.sinosoft.weixin.utils.ScmFileSystemUtils;
import javafx.scene.control.Cell;
import org.apache.commons.lang3.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * Created by huzhengying on 2017/12/25.
 */
@Controller
@RequestMapping("api/pdf")
public class ElecPlanBookController {
    private Logger mLogger = Logger.getLogger(ElecPlanBookController.class);

    @Value("${pdf.dir}")
    private String pdfDir;
    @Value("${font.dir}")
    private String fontDir;
    @Value("${template.path}")
    private String templatePath;
    @Value("${gcas.addr}")
    private String addr;
    @Autowired
    private InterfaceAdapterConfig interfaceAdapterConfig;
    ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("checkHavePlanBook")
    @ResponseBody
    public Object checkHavePlanBook(@RequestParam("riskAssessNo")String riskAssessNo){
        try{
            List<File> files = new ArrayList<>();
            ScmFileSystemUtils.searchFiles(riskAssessNo+".pdf",new File(pdfDir),files);
            if(files != null && files.size() > 0){
                return Vo.succ();
            }else {
                return Vo.fail("计划书不存在!");
            }
        }catch (Exception ex){
            return Vo.fail("查看计划书失败!");
        }

    }

    @RequestMapping("getElecPlanBook/{riskAssessNo}")
    public ResponseEntity<FileSystemResource> getElecPlanBook(@PathVariable("riskAssessNo")String riskAssessNo,ModelAndView mav) throws Exception{
        try{
            List<File> files = new ArrayList<>();
            ScmFileSystemUtils.searchFiles(riskAssessNo+".pdf",new File(pdfDir),files);
            if(files != null && files.size() > 0){
                return export(files.get(0));
            }else {
                RequestHeadDTO requestHeadDTO = new RequestHeadDTO(UUID.randomUUID().toString(),InterfaceAdapterConfig.QUERYPDF);
                RiskAssessDetailDTO riskAssessDetailDTO = new RiskAssessDetailDTO();
                riskAssessDetailDTO.setRiskAssessNo(riskAssessNo);
                RequestDTO requestDTO = new RequestDTO(requestHeadDTO,riskAssessDetailDTO);

                String queryResult = HttpClientUtils.sendHttpRequest(
                        objectMapper.writeValueAsString(requestDTO),
                        interfaceAdapterConfig.getContextUrl(InterfaceAdapterConfig.QUERYPDF));
                if(HttpClientUtils.fail_Result.equals(queryResult)){
                    throw new ServiceException("获取信息失败!");
                }
                HeadDTO headDTO = objectMapper.readValue(queryResult,HeadDTO.class);
                ElecPlanContentDTO elecPlanContentDTO = headDTO.getBody();
                createElecPlanBook(riskAssessNo,elecPlanContentDTO);

                return export(new File(pdfDir+riskAssessNo+".pdf"));
            }

        }catch (Exception ex){
            mLogger.error(ex);
            return export(new File(pdfDir+riskAssessNo+".pdf"));
        }
    }

    public void createElecPlanBook(String num, ElecPlanContentDTO elecPlanContentDTO){
        String liShu = fontDir+"SIMLI.TTF";
        final String fangSongTi = fontDir+"simsun_0.ttf";
        final String kaiTi = fontDir+"simsun_0.ttf";

        Document pdfDocument = new com.itextpdf.text.Document(PageSize.A4,2.5f,2.5f,2.5f,2.5f);
        String outFilePath = pdfDir+num+".pdf";
        try{
            PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(outFilePath));
            pdfDocument.open();
            PdfReader reader = new PdfReader(templatePath);

            for (int i = 1; i <= reader.getNumberOfPages(); i++){
                if(i == 1){
                    Font lishu = getFont(
                            liShu, BaseFont.IDENTITY_H, 30f, Font.NORMAL, BaseColor.BLACK);
                    PdfImportedPage page = writer.getImportedPage(reader, i);
                    Image image = Image.getInstance(page);
                    image.setAbsolutePosition(0,0);
                    pdfDocument.add(image);

                    Paragraph paragraph = new Paragraph();
                    paragraph.setAlignment(Element.ALIGN_CENTER);
                    paragraph.setIndentationLeft(35);
                    paragraph.setIndentationRight(35);
                    pdfDocument.add(new Phrase("\n\n\n\n\n\n\n\n"));
                    //设置公司名称
                    Chunk chunk = new Chunk(elecPlanContentDTO.getCompanyName()+"\n员工福利保障计划",lishu);
                    chunk.setLineHeight(25f);
                    paragraph.add(chunk);
                    pdfDocument.add(paragraph);
                    paragraph.clear();

                    Font fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,16f,Font.NORMAL,BaseColor.BLACK);
                    paragraph = new Paragraph();
                    paragraph.setAlignment(Element.ALIGN_CENTER);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月");
                    paragraph.add(
                            new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n国联人寿保险股份有限公司\n\n"+simpleDateFormat.format(new Date()),fangSong));

                    pdfDocument.add(paragraph);
                    paragraph.clear();
                    pdfDocument.newPage();
                }else if(i == 2){
                    PdfImportedPage page = writer.getImportedPage(reader, i);
                    Image image = Image.getInstance(page);
                    image.setAbsolutePosition(0,0);
                    pdfDocument.add(image);

                    Paragraph paragraph = new Paragraph();
                    Font fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,19f,Font.NORMAL,BaseColor.BLACK);
                    paragraph.add("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

                    paragraph.add(new Phrase(String.format("                                                %s\n\n\n\n",2),fangSong));
                    paragraph.add(new Phrase(String.format("                                                %s\n\n\n\n",3),fangSong));
                    paragraph.add(new Phrase(String.format("                                                %s\n\n\n\n",4),fangSong));
                    paragraph.add(new Phrase(String.format("                                                %s\n\n\n\n",6),fangSong));
                    paragraph.add(new Phrase(String.format("                                                %s\n\n\n\n",8),fangSong));
                    paragraph.add(new Phrase(String.format("                                                %s",9),fangSong));
                    pdfDocument.add(paragraph);
                    paragraph.clear();

                    paragraph = new Paragraph();
                    paragraph.setAlignment(Element.ALIGN_LEFT);
                    String pdf2PageContent = String.format("\n\n\n\n\n\n\n" +
                            "       服务人员:%s            服务电话:%s",
                            elecPlanContentDTO.getServiceName(),
                            elecPlanContentDTO.getServicePhone());
                    paragraph.add(new Phrase(pdf2PageContent,fangSong));
                    pdfDocument.add(paragraph);
                    paragraph.clear();

                    paragraph = new Paragraph();
                    paragraph.setAlignment(Element.ALIGN_CENTER);
                    paragraph.add(
                            new Phrase(String.format("\n\n\n地址:%s",elecPlanContentDTO.getServiceAddress()),fangSong));
                    pdfDocument.add(paragraph);
                    paragraph.clear();

                    pdfDocument.newPage();
                } else if(i==4){
                    PdfImportedPage page = writer.getImportedPage(reader, i);
                    Image image = Image.getInstance(page);
                    image.setAbsolutePosition(0,0);
                    pdfDocument.add(image);

                    Font fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,15f,Font.BOLD,BaseColor.BLACK);
                    Paragraph paragraph = new Paragraph();
                    paragraph.setAlignment(Element.ALIGN_LEFT);
                    paragraph.setIndentationLeft(40);
                    paragraph.setIndentationRight(40);
                    Chunk chunk = new Chunk(
                            String.format("\n\n\n\n\n\n致尊敬的%s:（以下简称贵公司）",elecPlanContentDTO.getCompanyName()),fangSong);
                    chunk.setLineHeight(25f);
                    paragraph.add(chunk);

                    pdfDocument.add(paragraph);
                    paragraph.clear();
                    pdfDocument.newPage();
                } else if(i == 7){
                    List<InsurePlanDTO> insurePlanDTOList = elecPlanContentDTO.getInsurancePlans();
                    for(int j=0;j<insurePlanDTOList.size();j++){
                        PdfImportedPage page;
                        if(j == 0){
                            page = writer.getImportedPage(reader, i);
                        }else {
                            page = writer.getImportedPage(reader, i+1);
                        }
                        Image image = Image.getInstance(page);
                        image.setAbsolutePosition(0,0);
                        pdfDocument.add(image);

                        Font fangSong = getFont(kaiTi,BaseFont.IDENTITY_H,28f,Font.BOLD,BaseColor.BLACK);
                        Paragraph paragraph = new Paragraph();
                        paragraph.setAlignment(Element.ALIGN_CENTER);
                        if(j==1){
                            paragraph.add(new Phrase("\n\n\n\n\n",fangSong));
                        }else {
                            paragraph.add(new Phrase("\n\n\n\n\n\n\n保险方案介绍",fangSong));
                        }
                        pdfDocument.add(paragraph);
                        paragraph.clear();

                        //获取方案内容
                        InsurePlanDTO insurePlanDTO = insurePlanDTOList.get(j);
                        //获取保障责任明细内容
                        List<InsureProjectDetailDTO> insureProjectDetailDTOs = insurePlanDTO.getDutys();
                        //获取特别约定
                        String specialAppointment = insurePlanDTO.getAppointment();
                        //获取保险期间
                        String insurancePeriod = insurePlanDTO.getInsurancePeriod();

                        //添加方案标题
                        paragraph = new Paragraph();
                        paragraph.setAlignment(Element.ALIGN_LEFT);
                        fangSong = getFont(kaiTi,BaseFont.IDENTITY_H,20f,Font.BOLD,BaseColor.BLACK);
                        paragraph.add(
                                new Phrase(
                                        String.format("\n\n    保险方案（%s）", ArabicToChineseUtils.foematInteger(j+1)),
                                        fangSong));
                        pdfDocument.add(paragraph);
                        paragraph.clear();

                        //添加保障责任表格
                        paragraph = new Paragraph();
                        paragraph.setAlignment(Element.ALIGN_LEFT);
                        fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,15f,Font.BOLD,BaseColor.BLACK);
                        paragraph.add(new Phrase("\n      保障责任\n\n", fangSong));
                        pdfDocument.add(paragraph);
                        paragraph.clear();

                        PdfPTable table = new PdfPTable(4);
                        //设置表格宽度
                        table.setWidthPercentage(85);
                        //设置表格位置
                        table.setHorizontalAlignment(Element.ALIGN_CENTER);
                        Font tableTileFont = getFont(fangSongTi,BaseFont.IDENTITY_H,12f,Font.BOLD,BaseColor.WHITE);
                        PdfPCell titleCell;
                        Paragraph titleParagraph = new Paragraph("员工福利保障计划",tableTileFont);
                        titleParagraph.setAlignment(Element.ALIGN_CENTER);
                        titleCell = new PdfPCell();
                        titleCell.setUseAscender(true);
                        titleCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                        titleCell.setBackgroundColor(new BaseColor(207,0,13));
                        titleCell.setColspan(4);
                        titleCell.setFixedHeight(25f);
                        titleCell.setPhrase(titleParagraph);
                        titleCell.setHorizontalAlignment(1);
                        table.addCell(titleCell);

                        PdfPCell contentCell;
                        fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,11f,Font.BOLD,BaseColor.BLACK);
                        contentCell = new PdfPCell(new Phrase("保险项目",fangSong));
                        contentCell.setFixedHeight(25f);
                        contentCell.setHorizontalAlignment(1);
                        table.addCell(contentCell);
                        contentCell = new PdfPCell(new Phrase("保险责任描述",fangSong));
                        contentCell.setHorizontalAlignment(1);
                        table.addCell(contentCell);
                        contentCell = new PdfPCell(new Phrase("保险金额（单位：元）",fangSong));
                        contentCell.setHorizontalAlignment(1);
                        table.addCell(contentCell);
                        contentCell = new PdfPCell(new Phrase("保费（单位：元）",fangSong));
                        contentCell.setHorizontalAlignment(1);
                        table.addCell(contentCell);

                        fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,10f,Font.NORMAL,BaseColor.BLACK);

                        for(int a=0;a<insureProjectDetailDTOs.size();a++){
                            InsureProjectDetailDTO insureProjectDetailDTO = insureProjectDetailDTOs.get(a);
                            contentCell = new PdfPCell(new Phrase(insureProjectDetailDTO.getProjectName(),fangSong));
                            contentCell.setFixedHeight(20f);
                            contentCell.setHorizontalAlignment(1);
                            table.addCell(contentCell);

                            contentCell = new PdfPCell(new Phrase(insureProjectDetailDTO.getDutyDescribe(),fangSong));
                            contentCell.setHorizontalAlignment(1);
                            table.addCell(contentCell);
                            if("附加意外伤害住院补贴团体医疗保险".equals(insureProjectDetailDTO.getDutyDescribe())){
                                contentCell = new PdfPCell(new Phrase(insureProjectDetailDTO.getInsuranceMoney()+"元/天",fangSong));
                            }else {
                                contentCell = new PdfPCell(new Phrase(insureProjectDetailDTO.getInsuranceMoney(),fangSong));

                            }
                            contentCell.setHorizontalAlignment(1);
                            table.addCell(contentCell);
                            contentCell = new PdfPCell(new Phrase(insureProjectDetailDTO.getPrem(),fangSong));
                            contentCell.setHorizontalAlignment(1);
                            table.addCell(contentCell);
                        }
                        pdfDocument.add(table);
                        //保险期间
                        //添加特别约定
                        if(org.apache.commons.lang3.StringUtils.isNotBlank(specialAppointment)){
                            fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,15f,Font.BOLD,BaseColor.BLACK);
                            paragraph = new Paragraph();
                            paragraph.add(new Phrase("\r\n      "+insurancePeriod+"\r\n", fangSong));
                            pdfDocument.add(paragraph);
                            paragraph.clear();
                            paragraph = new Paragraph();
                            fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,15f,Font.BOLD,BaseColor.BLACK);
                            paragraph.add(new Phrase("\n      特别约定\n", fangSong));
                            pdfDocument.add(paragraph);
                            paragraph.clear();
                            paragraph = new Paragraph();
                            paragraph.setIndentationLeft(36);
                            paragraph.setIndentationRight(36);
                            fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,13f,Font.NORMAL,BaseColor.BLACK);

                            specialAppointment = specialAppointment.replace("2.","\r\n    2.");
                            specialAppointment = specialAppointment.replace("3.","\r\n    3.");
                            specialAppointment = specialAppointment.replace("4.","    4.");
                            Chunk chunk = new Chunk(specialAppointment,fangSong);
                            chunk.setLineHeight(21f);

                            paragraph.add(chunk);
                            pdfDocument.add(paragraph);
                            paragraph.clear();
                        }

                        pdfDocument.newPage();
                    }
                }else if(i == 8){
                    continue;
                }else if(i == 10){
                    PdfImportedPage page = writer.getImportedPage(reader,10);
                    Image image = Image.getInstance(page);
                    image.setAbsolutePosition(0,0);
                    pdfDocument.add(image);

                    Paragraph paragraph = new Paragraph();
                    paragraph.setAlignment(Element.ALIGN_LEFT);
                    Font fangSong = getFont(fangSongTi,BaseFont.IDENTITY_H,14f,Font.NORMAL,BaseColor.BLACK);
                    List<ClauseDetailDTO> clauseDetailDTOS = elecPlanContentDTO.getClauses();
                    paragraph.add("\n\n\n\n\n\n\n\n\n\n\n\n\n");
                    for(ClauseDetailDTO clauseDetailDTO : clauseDetailDTOS){
                        paragraph.add(new Phrase("          "+clauseDetailDTO.getClauseName()+"\n\n",fangSong));
                    }
                    pdfDocument.add(paragraph);
                    paragraph.clear();

                    pdfDocument.newPage();
                } else {
                    PdfImportedPage page = writer.getImportedPage(reader, i);
                    Image image = Image.getInstance(page);
                    image.setAbsolutePosition(0,0);
                    pdfDocument.add(image);
                    pdfDocument.newPage();
                }

            }

        }catch (Exception e) {
            pdfDocument.close();
            throw new ServiceException("生成pdf失败!",e);
        } finally {
            pdfDocument.close();
        }
    }

    private static Font getFont(String fontTtfUrl,String encoding,Float fontSize,int fontWide,BaseColor baseColor) throws Exception{
        BaseFont baseFont = BaseFont.createFont(
                fontTtfUrl,
                encoding,
                BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont,fontSize,fontWide,baseColor);
        return font;
    }

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename="+file.getName());
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }
}
